#include "stdafx.h"
#include "wf_drawspline.h"



WF_DrawSpline::WF_DrawSpline(PF_Container& container,
                                     PF_GraphicView& graphicView)
        :PF_PreviewActionInterface("Draw splines",
                           container, graphicView) {

    reset();
    data = PF_SplineAttribute(3, false);
}



WF_DrawSpline::~WF_DrawSpline() {}


QAction* WF_DrawSpline::createGUIAction(LX_Define::ActionType /*type*/, QObject* /*parent*/) {
	// tr("Spline")
    QAction* action = new QAction(tr("&Spline"),  NULL);
	action->setIcon(QIcon(":/extui/menuspline.png"));
    //action->zetStatusTip(tr("Draw splines"));
    return action;
}



void WF_DrawSpline::reset() {
	spline = NULL;
    //start = PF_Vector(false);
    history.clear();
    //bHistory.clear();
}



void WF_DrawSpline::init(int status) {
    PF_PreviewActionInterface::init(status);

    reset();
}



void WF_DrawSpline::trigger() {
    PF_PreviewActionInterface::trigger();

	if (spline==NULL) {
		return;
	}

	// add the entity
    //PF_Spline* spline = new PF_Spline(container, data);
    spline->setLayerToActive();
    spline->setPenToActive();
	spline->update();
    container->addEntity(spline);

    // upd. undo list:
    if (document!=NULL) {
        document->startUndoCycle();
        document->addUndoable(spline);
        document->endUndoCycle();
    }

	// upd view
	PF_Vector r = graphicView->getRelativeZero();
	graphicView->redraw(LX_Define::RedrawDrawing);
    graphicView->moveRelativeZero(r);
    PF_DEBUG->print("PF_ActionDrawSpline::trigger(): spline added: %d",
                    spline->getId());

	spline = NULL;
    //history.clear();
}



void WF_DrawSpline::mouseMoveEvent(QMouseEvent* e) {
    PF_DEBUG->print("PF_ActionDrawSpline::mouseMoveEvent begin");

    PF_Vector mouse = snapPoint(e);
    if (getStatus()==SetNextPoint && spline!=NULL /*&& point.valid*/) {
        deletePreview();
		
		PF_Spline* tmpSpline = (PF_Spline*)spline->clone();
		tmpSpline->addControlPoint(mouse);
		tmpSpline->update();
		preview->addEntity(tmpSpline);
		
                QList<PF_Vector> cpts = tmpSpline->getControlPoints();
                for (int i = 0; i < cpts.size(); ++i) {
                        preview->addEntity(new PF_Point(preview, PF_PointAttribute(cpts.at(i))));
                }
        drawPreview();
    }

    PF_DEBUG->print("PF_ActionDrawSpline::mouseMoveEvent end");
}



void WF_DrawSpline::mouseReleaseEvent(QMouseEvent* e) {
    if (e->button()==Qt::LeftButton) {
        PF_CoordinateEvent ce(snapPoint(e));
        coordinateEvent(&ce);
    } else if (e->button()==Qt::RightButton) {
		if (getStatus()==SetNextPoint) {
			trigger();
		}
        deletePreview();
        init(getStatus()-1);
    }
}



void WF_DrawSpline::coordinateEvent(PF_CoordinateEvent* e) {
    if (e==NULL) {
        return;
    }

    PF_Vector mouse = e->getCoordinate();

    switch (getStatus()) {
    case SetStartpoint:
		//data.startpoint = mouse;
        //point = mouse;
        history.clear();
        history.append(mouse);
		if (spline==NULL) {
			spline = new PF_Spline(container, data);
			spline->addControlPoint(mouse);
		}
        //bHistory.clear();
        //bHistory.append(new double(0.0));
        //start = mouse;
        setStatus(SetNextPoint);
        graphicView->moveRelativeZero(mouse);
        updateMouseButtonHints();
        break;

    case SetNextPoint:
    	graphicView->moveRelativeZero(mouse);
        //point = mouse;
        history.append(mouse);
        //bHistory.append(new double(0.0));
		if (spline!=NULL) {
			//graphicView->deleteEntity(spline);
			spline->addControlPoint(mouse);
			//spline->setEndpoint(mouse);
			//if (spline->count()==1) {
    			//spline->setLayerToActive();
    			//spline->setPenToActive();
				//container->addEntity(spline);
			//}
			deletePreview();
			//graphicView->drawEntity(spline);
			drawSnapper();
		}
        //trigger();
        //data.startpoint = data.endpoint;
        updateMouseButtonHints();
        //graphicView->moveRelativeZero(mouse);
        break;

    default:
        break;
    }
}



void WF_DrawSpline::commandEvent(PF_CommandEvent* e) {
    QString c = e->getCommand().toLower();

    switch (getStatus()) {
    case SetStartpoint:
        if (checkCommand("help", c)) {
            PF_DIALOGFACTORY->commandMessage(msgAvailableCommands()
                                             + getAvailableCommands().join(", "));
            return;
        }
        break;

    case SetNextPoint:
        /*if (checkCommand("close", c)) {
            close();
            updateMouseButtonHints();
            return;
        }*/

        if (checkCommand("undo", c)) {
            undo();
            updateMouseButtonHints();
            return;
        }
        break;

    default:
        break;
    }
}



QStringList WF_DrawSpline::getAvailableCommands() {
    QStringList cmd;

    switch (getStatus()) {
    case SetStartpoint:
        break;
    case SetNextPoint:
        if (history.size()>=2) {
            cmd += command("undo");
        }
        if (history.size()>=3) {
            cmd += command("close");
        }
        break;
    default:
        break;
    }

    return cmd;
}



void WF_DrawSpline::updateMouseButtonHints() {
    switch (getStatus()) {
    case SetStartpoint:
        PF_DIALOGFACTORY->updateMouseWidget(tr("Specify first control point"),
                                            tr("Cancel"));
        break;
    case SetNextPoint: {
            QString msg = "";

            if (history.size()>=3) {
                msg += PF_COMMANDS->command("close");
                msg += "/";
            }
            if (history.size()>=2) {
                msg += PF_COMMANDS->command("undo");
            }

            if (history.size()>=2) {
                PF_DIALOGFACTORY->updateMouseWidget(
                    tr("Specify next control point or [%1]").arg(msg),
                    tr("Back"));
            } else {
                PF_DIALOGFACTORY->updateMouseWidget(
                    tr("Specify next control point"),
                    tr("Back"));
            }
        }
        break;
    default:
        PF_DIALOGFACTORY->updateMouseWidget("", "");
        break;
    }
}


void WF_DrawSpline::showOptions() {
    PF_ActionInterface::showOptions();

    PF_DIALOGFACTORY->requestOptions(this, true);
}



void WF_DrawSpline::hideOptions() {
    PF_ActionInterface::hideOptions();

    PF_DIALOGFACTORY->requestOptions(this, false);
}


void WF_DrawSpline::updateMouseCursor() {
    graphicView->setMouseCursor(LX_Define::CadCursor);
}


void WF_DrawSpline::updateToolBar() {
    if (!isFinished()) {
        PF_DIALOGFACTORY->requestToolBar(LX_Define::ToolBarSnap);
    } else {
        //PF_DIALOGFACTORY->requestToolBar(LX_Define::ToolBarSplines);
        PF_DIALOGFACTORY->requestToolBar(LX_Define::ToolBarMain);
    }
}


/*
void PF_ActionDrawSpline::close() {
    if (history.count()>2 && start.valid) {
        //data.endpoint = start;
        //trigger();
		if (spline!=NULL) {
			PF_CoordinateEvent e(spline->getStartpoint());
			coordinateEvent(&e);
		}
		trigger();
        setStatus(SetStartpoint);
        graphicView->moveRelativeZero(start);
    } else {
        PF_DIALOGFACTORY->commandMessage(
            tr("Cannot close sequence of lines: "
               "Not enough entities defined yet."));
    }
}
*/

void WF_DrawSpline::undo() {
    if (history.size()>1) {
        history.removeLast();
        //bHistory.removeLast();
        deletePreview();
        //graphicView->setCurrentAction(
        //    new PF_ActionEditUndo(true, *container, *graphicView));
                if (!history.isEmpty()) {
        	//point = *history.last();
		}
		if (spline!=NULL) {
			spline->removeLastControlPoint();
                        if (!history.isEmpty()) {
                            PF_Vector v = history.last();
                            graphicView->moveRelativeZero(v);
                        }
			graphicView->redraw(LX_Define::RedrawDrawing); 

		}
    } else {
        PF_DIALOGFACTORY->commandMessage(
            tr("Cannot undo: "
               "Not enough entities defined yet."));
    }
}


void WF_DrawSpline::setDegree(int deg) {
	data.degree = deg;
	if (spline!=NULL) {
		spline->setDegree(deg);
	}
}

int WF_DrawSpline::getDegree() {
	return data.degree;
}

void WF_DrawSpline::setClosed(bool c) {
	data.closed = c;
	if (spline!=NULL) {
		spline->setClosed(c);
	}
}

bool WF_DrawSpline::isClosed() {
	return data.closed;
}

// EOF
